package com.nbicc.dp.wsgateway.Handler;

import com.nbicc.core.utils.ExceptionUtil;
import com.nbicc.dp.wsgateway.annotation.WsRequestTagMapping;
import com.nbicc.dp.wsgateway.common.ObjectAndMethod;
import com.nbicc.dp.wsgateway.common.WsRequest;
import com.nbicc.dp.wsgateway.common.WsRequestMapping;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lilingyan
 */
@Slf4j
@Component
public class WsRequestMappingHandler {

    @Autowired
    private Map<String , WsRequestMapping> wsRequestMappingMap;

    private Map<String , ObjectAndMethod> methodMap = new HashMap<>();

    @PostConstruct
    private void init(){
        if(wsRequestMappingMap != null && wsRequestMappingMap.size()>0){
            for (WsRequestMapping wsRequestMapping : wsRequestMappingMap.values()) {
                Method[] methods = wsRequestMapping.getClass().getMethods();
                for (Method method : methods) {
                    WsRequestTagMapping wsRequestTagMapping = method.getAnnotation(WsRequestTagMapping.class);
                    if(wsRequestTagMapping != null){
                        ObjectAndMethod om = new ObjectAndMethod();
                        om.setObject(wsRequestMapping);
                        om.setMethod(method);
                        methodMap.put(wsRequestTagMapping.value() , om);
                    }
                }
            }
        }
    }

    public void executeByTag(WebSocketSession session , WsRequest wsRequest){
        ObjectAndMethod objectAndMethod = methodMap.get(wsRequest.getTag());
        if(objectAndMethod != null){
            try {
                objectAndMethod.getMethod().invoke(objectAndMethod.getObject() , session,wsRequest);
            } catch (Exception e) {
                log.error(ExceptionUtil.getStackTraceInfo(e));
            }
        }
    }

}
